<script setup lang="tsx">
import { ContentWrap } from '@/components/ContentWrap'
import { useI18n } from '@/hooks/web/useI18n'
import { Table } from '@/components/Table'
import { ref, unref, reactive } from 'vue'
// import { ElTree, ElInput, ElDivider } from 'element-plus'
import { getNoticeApi, saveNoticeApi, deleteNoticeByIdApi } from '@/api/notice'
import type { NoticeItem } from '@/api/notice/types'
import { useTable } from '@/hooks/web/useTable'
import { Search } from '@/components/Search'
import Write from './components/Write.vue'
import { Dialog } from '@/components/Dialog'
// import { getRoleListApi } from '@/api/role'
import { useEventBus } from '@/hooks/event/useEventBus'
import { CrudSchema, useCrudSchemas } from '@/hooks/web/useCrudSchemas'
import { BaseButton } from '@/components/Button'
import { ElMessage } from 'element-plus'

const { t } = useI18n()

const { tableRegister, tableState, tableMethods } = useTable({
  fetchDataApi: async () => {
    const { pageSize, currentPage } = tableState
    const res = await getNoticeApi({
      pageNum: unref(currentPage),
      pageSize: unref(pageSize),
      ...unref(searchParams)
    })
    return {
      list: res.data.list || [],
      total: res.data.total || 0
    }
  },
  fetchDelApi: async () => {
    const res = await deleteNoticeByIdApi(unref(ids))
    return !!res
  }
})
const { total, loading, dataList, pageSize, currentPage } = tableState
const { getList, getElTableExpose, delList } = tableMethods

useEventBus({
  name: 'getList',
  callback: (type: string) => {
    if (type === 'add') {
      currentPage.value = 1
      dialogVisible.value = false
    }
    getList()
  }
})

const writeRef = ref<ComponentRef<typeof Write>>()

const crudSchemas = reactive<CrudSchema[]>([
  {
    field: 'selection',
    search: {
      hidden: true
    },
    form: {
      hidden: true
    },
    table: {
      type: 'selection'
    }
  },
  {
    field: 'id',
    label: t('user.id'),
    form: {
      hidden: true
    },
    search: {
      hidden: true
    }
  },
  {
    field: 'title',
    label: t('system.noticeTitle'),
    form: {
      colProps: {
        span: 24
      }
    }
  },
  {
    field: 'content',
    label: t('system.noticeContent'),
    form: {
      component: 'Editor',
      colProps: {
        span: 24
      },
      componentProps: {
        defaultHtml: '',
        height: '200px',
        // @ts-ignore
        onChange: (edit: IDomEditor) => {
          const write = unref(writeRef)
          write.setContent(edit.getHtml())
        }
      }
    },
    table: {
      hidden: true
    },
    search: {
      hidden: true
    }
  },
  {
    field: 'addTime',
    label: t('system.noticeAddTime'),
    form: {
      hidden: true
    },
    search: {
      hidden: true
    }
  },
  {
    field: 'action',
    label: t('user.action'),
    form: {
      hidden: true
    },
    detail: {
      hidden: true
    },
    search: {
      hidden: true
    },
    table: {
      slots: {
        default: (data: any) => {
          const row = data.row as NoticeItem
          return (
            <>
              <BaseButton type="primary" onClick={() => action(row, 'edit')}>
                {t('baseDesc.edit')}
              </BaseButton>
              <BaseButton type="danger" onClick={() => delData(row)}>
                {t('baseDesc.del')}
              </BaseButton>
            </>
          )
        }
      }
    }
  }
])

const { allSchemas } = useCrudSchemas(crudSchemas)

const searchParams = ref({})
const setSearchParams = (params: any) => {
  currentPage.value = 1
  searchParams.value = params
  getList()
}

const dialogVisible = ref(false)
const dialogTitle = ref('')

const currentRow = ref<NoticeItem>()
const actionType = ref('')

const AddAction = () => {
  dialogTitle.value = t('baseDesc.add')
  currentRow.value = undefined
  dialogVisible.value = true
  actionType.value = ''
}

const delLoading = ref(false)
const ids = ref<string[]>([])

const delData = async (row?: NoticeItem) => {
  const elTableExpose = await getElTableExpose()
  ids.value = row ? [row.id] : elTableExpose?.getSelectionRows().map((v: NoticeItem) => v.id) || []
  delLoading.value = true

  await delList(unref(ids).length).finally(() => {
    delLoading.value = false
  })
}

const action = (row: NoticeItem, type: string) => {
  dialogTitle.value = t('exampleDemo.edit')
  actionType.value = type
  currentRow.value = { ...row }
  dialogVisible.value = true
}

const saveLoading = ref(false)

const save = async () => {
  const write = unref(writeRef)
  const formData = await write?.submit()
  if (formData) {
    saveLoading.value = true
    saveNoticeApi(formData)
      .then((res) => {
        console.log(res)
        if (res.code != 200) {
          ElMessage.error(res.message)
        } else {
          ElMessage.success({
            duration: 1000,
            message: res.message,
            onClose: () => {
              currentPage.value = 1
              getList()
              saveLoading.value = false
              dialogVisible.value = false
            }
          })
        }
      })
      .catch((err) => {
        console.log(err)
        ElMessage.error(err)
      })
  }
}
</script>

<template>
  <div class="flex w-100% h-100%">
    <ContentWrap class="flex-[3]">
      <Search
        :schema="allSchemas.searchSchema"
        @reset="setSearchParams"
        @search="setSearchParams"
      />

      <div class="mb-10px">
        <BaseButton type="primary" @click="AddAction">{{ t('baseDesc.add') }}</BaseButton>
        <BaseButton :loading="delLoading" type="danger" @click="delData()">
          {{ t('baseDesc.del') }}
        </BaseButton>
      </div>
      <Table
        v-model:current-page="currentPage"
        v-model:page-size="pageSize"
        :columns="allSchemas.tableColumns"
        :data="dataList"
        :loading="loading"
        @register="tableRegister"
        :pagination="{
          total
        }"
      />
    </ContentWrap>

    <Dialog v-model="dialogVisible" :title="dialogTitle">
      <Write
        v-if="actionType !== 'detail'"
        ref="writeRef"
        :form-schema="allSchemas.formSchema"
        :current-row="currentRow"
      />

      <template #footer>
        <BaseButton
          v-if="actionType !== 'detail'"
          type="primary"
          :loading="saveLoading"
          @click="save"
        >
          {{ t('exampleDemo.save') }}
        </BaseButton>
        <BaseButton @click="dialogVisible = false">{{ t('dialogDemo.close') }}</BaseButton>
      </template>
    </Dialog>
  </div>
</template>
